
import ls from "../local-storage";
import WebResult from "./web-result";

export async function register({
    username,
    email,
    password
}) {
    let users = ls.get("users");
    if (!users) {
        users = [];
    }
    if (users.find(user => user.username === username)) {
        return WebResult.failed(undefined, "用户名已被使用");
    }
    users.push({
        username,
        email,
        password
    });
    ls.set("users", users);
    return WebResult.success(undefined, "注册成功");
}

export async function login({username, password}) {
    console.log(username, password);
    let users = ls.get("users");
    if (!users) {
        users = [];
    }
    const wannaLoginUser = users.find((user) => user.username === username);
    if (!wannaLoginUser) {
        return WebResult.failed(undefined, "用户不存在");
    }
    if (password !== wannaLoginUser.password) {
        return WebResult.failed(undefined, "用户名或密码错误");
    }
    ls.set("user", wannaLoginUser);
    return WebResult.success(undefined, "登录成功");
}


export async function getUserInfo() {
    const user = ls.get("user");
    if (!user) {
        return WebResult.failed(undefined, "未登录");
    }
    return WebResult.success({
        username: user.username,
        email: user.email
    });
}

export function logout() {
    ls.remove("user");
}

